import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:znmm/UI/A_Common/buttons/easy_button/easy_elevated_button.dart';
import 'package:znmm/UI/A_Common/dialogs/cn_custom_dialog.dart';
import 'package:znmm/UI/LoginPages/mag/user_info_manage.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/config/app_color.dart';
import 'package:znmm/network/notify_listener.dart';
import '../A_Common/custom_web_view.dart';
import 'mag/cart_mag.dart';
import 'model/cart_model.dart';
import 'view/cart_cell.dart';

class CnCartPage extends StatefulWidget {
  const CnCartPage({super.key});

  @override
  State<CnCartPage> createState() => _CnCartPageState();
}

class _CnCartPageState extends State<CnCartPage> {
  Future<List<CnCartModel>>? _cartModelList;
  int _iNotiId1 = -1;

  @override
  void initState() {
    super.initState();

    _cartModelList = CnCartMag().getCartProductList();

    //添加监听者
    _iNotiId1 = NotifyCenter().addObserver(NotifyKey.cartProductKey, (object) {
      if (mounted) {
        setState(() {
          _cartModelList = CnCartMag().getCartProductList();
        });
      }
    });

    //--------------------网络请求购物车数据
    CnCartMag().reqCartData();
  }

  @override
  void dispose() {
    NotifyCenter().removeCallback(_iNotiId1);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppColor.backgroundColor,
        appBar: MyGlobal.getNavigationBar(context, "Cart",
            backWidget: const SizedBox(),
            actions: [
              if (!UserInfoMag().bIsVisito)
                IconButton(
                  onPressed: () {
                    CnCartMag().reqCartData();

                    // if (UserInfoMag().bIsVisito) {
                    //   showDialog(
                    //     context: context,
                    //     builder: (context) => const CustomDialog(
                    //       content: 'Please Login?',
                    //       confirmText: "Login",
                    //     ),
                    //   ).then((value) {
                    //     if (value != null && value) {
                    //       AppInit.logoutDispose();
                    //     }
                    //   });
                    //   return;
                    // }
                    // CnCartMag().saveCartModelList();
                  },
                  icon: const Icon(Icons.refresh),
                  tooltip: 'refresh',
                  color: Colors.black,
                )
            ]),
        body: FutureBuilder<List<CnCartModel>>(
          future: _cartModelList,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator()); // 加载中
            } else if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}')); // 加载失败
            } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
              return Column(
                children: [
                  Container(
                      margin: const EdgeInsets.only(top: 10),
                      height: 30,
                      padding: const EdgeInsets.only(left: 20, right: 20),
                      child: const Row(
                        children: [
                          Text(
                            "Shopping Bag (0)",
                            style: TextStyle(
                                fontSize: 18, fontWeight: FontWeight.bold),
                          ),
                          Spacer(),
                        ],
                      )),
                  const SizedBox(
                    height: 100,
                  ),
                  MyGlobal.emptyWidget()
                ],
              ); // 数据为空
            } else {
              final cartItems = snapshot.data!; // 数据加载成功
              return Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // title
                  Container(
                    margin: const EdgeInsets.only(top: 10),
                    height: 30,
                    padding: const EdgeInsets.only(left: 20, right: 20),
                    child: Row(
                      children: [
                        Text(
                          "Shopping Bag (${cartItems.length})",
                          style: const TextStyle(
                              fontSize: 18, fontWeight: FontWeight.bold),
                        ),
                        const Spacer(),
                      ],
                    ),
                  ),

                  Expanded(
                    child: MediaQuery.removePadding(
                        removeTop: true,
                        context: context,
                        child: ListView.separated(
                          //shrinkWrap: true,
                          //reverse: true,
                          //physics: const ClampingScrollPhysics(),
                          itemCount: cartItems.length,
                          separatorBuilder: (BuildContext context, int index) {
                            return const Divider(
                              height: 0.2,
                              thickness: 0.2,
                              color: Colors.grey,
                            );
                          },
                          itemBuilder: (_, index) {
                            CnCartModel pModel = cartItems[index];
                            return Padding(
                              padding: const EdgeInsets.all(4),
                              child: CnCartCell(
                                pModel: pModel,
                                onCallBack: (model, iCount) {
                                  print("iCount:$iCount");

                                  CnCartMag().reqIncrementQtNum(
                                    itemKey: model.itemKey,
                                    quantity: model.iqty + iCount,
                                    callback: () {
                                      if (mounted) {
                                        setState(() {});
                                      }
                                    },
                                  );

                                  // CnCartMag()
                                  //     .addAnRemQtNum(model.id, iCount, context);
                                },
                                removeBack: (model) {
                                  showDialog(
                                    context: context,
                                    builder: (context) => CustomDialog(
                                      //title: 'Confirmation',
                                      content: 'Remove from your cart?',
                                      onConfirm: () {
                                        // 这里处理确认按钮的逻辑
                                        print('Confirmed');
                                        CnCartMag().reqIncrementQtNum(
                                          itemKey: model.itemKey,
                                          quantity: 0,
                                          callback: () {
                                            if (mounted) {
                                              setState(() {});
                                            }
                                          },
                                        );
                                      },
                                    ),
                                  );

                                  //CnCartMag().removeCart(context, model);
                                },
                              ),
                            );
                          },
                        )),
                  ),
                  _bottomView()
                ],
              );
            }
          },
        ));
  }

  // void _requestOpion(String itemKey, int quantity) {
  //   CnCartMag().reqIncrementQtNum(
  //     itemKey: itemKey,
  //     quantity: quantity,
  //     callback: () {
  //       if (mounted) {
  //         setState(() {});
  //       }
  //     },
  //   );
  // }

  Widget _bottomView() {
    return Container(
      height: 150,
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.white,
          width: 0.5,
        ),
      ),
      padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 1.标题
          const Text(
            "Order Summary",
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          const SizedBox(
            height: 10,
          ),
          // 2.小计
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text("Subtotal:"),
              Text(
                CnCartMag().totalPriceStr,
              )
            ],
          ),
          const SizedBox(
            height: 10,
          ),
          // 3.结算checkout
          Expanded(
              child: Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  width: 2,
                  color: AppColor.grey.withOpacity(0.1),
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 价格
                RichText(
                  text: TextSpan(
                      text: "Grand Total: ",
                      style: const TextStyle(color: Colors.black),
                      children: [
                        TextSpan(
                            text: CnCartMag().totalPriceStr,
                            style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 20,
                                color: Colors.black)),
                      ]),
                ),
                // 按钮
                EasyElevatedButton(
                  label: 'Check Out',
                  isRounded: true,
                  color: Colors.black,
                  onPressed: () {
                    Get.to(const CustomWebView(
                      titleStr: "",
                      bIsShowTips: true,
                      initialUrl: "https://www.glassesin.com/",
                    ));
                  },
                )
              ],
            ),
          ))
        ],
      ),
    );
  }
}


/*

    showDialog(
                                  context: context,
                                  builder: (context) => CustomDialog(
                                    //title: 'Confirmation',
                                    content: 'Remove from your cart?',
                                    onConfirm: () {
                                      // 这里处理确认按钮的逻辑
                                      print('Confirmed');
                                      // String itemKey =
                                      //     model.item_key.toString();

                                      // _requestOpion(itemKey, 0);
                                    },
                                  ),
                                );

*/